from datetime import datetime

from django.shortcuts import render

# Create your views here.


# 用户名是否存在
#  GET usernames/(?P<username>\w{5,20})/count/
from django_redis import get_redis_connection
from rest_framework import mixins

from rest_framework import status
from rest_framework.decorators import action
from rest_framework.generics import CreateAPIView
from rest_framework.generics import GenericAPIView, RetrieveAPIView
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.permissions import IsAuthenticated
from rest_framework.viewsets import GenericViewSet
from rest_framework_jwt.settings import api_settings
from rest_framework_jwt.views import ObtainJSONWebToken, jwt_response_payload_handler

from cart.utils import merge_cookie_cart_to_redis
from goods.models import SKU
from goods.serializers import SKUSerializers
from users import constants
from users import serializers
from users.models import User

# 用户名是否存在
from users.serializers import CreateUserSerializer, UserDetailSerializer, EmailSerializer, UserAddressSerializer, \
    HistorySeralizer


class UsernameCountView(APIView):
    '''
    用户名是否存在
    '''

    def get(self, requset, username):
        count = User.objects.filter(username=username).count()

        data = {
            "username": username,
            "count": count
        }

        return Response(data=data)


# 判断手机号是否存在
#  GET mobiles/(?P<mobile>1[3-9]\d{9})/count/
class MobileCountView(APIView):
    '''
    手机手机号是否存在 返回数量
    '''

    def get(self, request, mobile):
        count = User.objects.filter(mobile=mobile).count()
        data = {
            "mobile": mobile,
            "count": count
        }
        return Response(data=data)


# 注册
# POST /users/

class UserView(CreateAPIView):
    """
    用户注册
        username, password, password2, sms_code, mobile, allow
        1. 获取参数  用户名 密码 密码2 手机验证码  电话号  是否勾选同意
        2. 校验参数完整性
        3. 校验参数
        4. 保存用户-----密码加密在保存
        5. 返回 用户名 ID  token(状态保持)

    """
    serializer_class = CreateUserSerializer


# 用户详情
#  GET /user/
# class UserDetailView(GenericAPIView):
class UserDetailView(RetrieveAPIView):
    '''
    用户详情
    1. 添加权限,认证用户才可以访问
    2. 获取用户
    3. 序列化返回id username, mobile, email, email_active
    '''
    # 1. 添加权限,认证用户才可以访问
    permission_classes = [IsAuthenticated]
    serializer_class = UserDetailSerializer

    def get_object(self):
        '''获取用户'''
        return self.request.user

        # def get(self, request):
        #     # 2. 获取用户
        #     # user = request.user
        #     user = self.get_object()
        #
        #     # 3. 序列化返回id username, mobile, email, email_active
        #     serializer = self.get_serializer(user)
        #     return Response(serializer.data)


# 设置邮箱及验证邮箱
# PUT /email/
class EmailView(GenericAPIView):
    '''
    设置邮箱及验证邮箱
    1. 获取邮箱并验证
    2. 保存邮箱地址 & 发送验证邮件到用户
    3. 返回 id, email
    '''
    serializer_class = EmailSerializer
    permission_classes = [IsAuthenticated]

    def put(self, request):
        user = request.user
        # 1. 获取邮箱并验证
        serializer = self.get_serializer(user, data=request.data)
        serializer.is_valid(raise_exception=True)

        # 2. 保存邮箱地址 & 发送验证邮件到用户

        serializer.save()
        # 3. 返回 id, email

        return Response(serializer.data)


# 验证邮箱链接
# PUT /emails/verification/?token=xxx
class VerifyEmailView(APIView):
    '''
    验证邮箱链接
    1. 获取查询字符串中的token
    2. 对token解密 ,验证token
    3. 修改 email_active 字段状态
    4. 返回ok
    '''

    def put(self, request):

        # 1. 获取查询字符串中的token
        token = request.query_params.get("token")
        if not token:
            return Response({'message': '缺少参数token'}, status=status.HTTP_400_BAD_REQUEST)

        # 验证token
        user = User.check_verify_email_token(token)
        # 3. 修改 email_active 字段状态
        if user is None:
            return Response({'message': 'token无效'})
        else:
            user.email_active = True
            user.save()

        # 4. 返回ok
        return Response({'message': 'OK'})


# 添加收货地址
# POST /addresses/
class AddressViewSet(mixins.CreateModelMixin, mixins.UpdateModelMixin, GenericViewSet):
    """
    用户地址新增与修改
    """
    serializer_class = serializers.UserAddressSerializer
    permissions = [IsAuthenticated]

    def get_queryset(self):
        return self.request.user.addresses.filter(is_deleted=False)

    # GET /addresses/
    def list(self, request, *args, **kwargs):
        """
        用户地址列表数据
        """
        queryset = self.get_queryset()
        serializer = self.get_serializer(queryset, many=True)
        user = self.request.user
        return Response({
            'user_id': user.id,
            'default_address_id': user.default_address_id,
            'limit': constants.USER_ADDRESS_COUNTS_LIMIT,
            'addresses': serializer.data,
        })

    # POST /addresses/
    def create(self, request, *args, **kwargs):
        """
        保存用户地址数据
        """
        # 检查用户地址数据数目不能超过上限
        count = request.user.addresses.filter(is_deleted=False).count()
        if count >= constants.USER_ADDRESS_COUNTS_LIMIT:
            return Response({'message': '保存地址数据已达到上限'}, status=status.HTTP_400_BAD_REQUEST)

        return super().create(request, *args, **kwargs)

    # delete /addresses/<pk>/
    def destroy(self, request, *args, **kwargs):
        """
        处理删除
        """
        address = self.get_object()

        # 进行逻辑删除
        address.is_deleted = True
        address.save()

        return Response(status=status.HTTP_204_NO_CONTENT)

    # put /addresses/pk/status/
    @action(methods=['put'], detail=True)
    def status(self, request, pk=None):
        """
        设置默认地址
        """
        address = self.get_object()
        request.user.default_address = address
        request.user.save()
        return Response({'message': 'OK'}, status=status.HTTP_200_OK)

    # put /addresses/pk/title/
    # 需要请求体参数 title
    @action(methods=['put'], detail=True)
    def title(self, request, pk=None):
        """
        修改标题
        """
        address = self.get_object()
        serializer = serializers.AddressTitleSerializer(instance=address, data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data)



#
# class Tubiao(APIView):
#     def get(self):
#         return render('/home/python/Desktop/twelfth/meiduo_mall/meiduo_mall/templates/1.jpg')
#
#






# 继承登录视图 ObtainJSONWebToken 重写登录post代码 添加调用合并购物车函数
class UserAuthorizeView(ObtainJSONWebToken):
    """
    用户认证
    """

    def post(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)

        if serializer.is_valid():
            user = serializer.object.get('user') or request.user
            token = serializer.object.get('token')
            response_data = jwt_response_payload_handler(token, user, request)
            response = Response(response_data)
            if api_settings.JWT_AUTH_COOKIE:
                expiration = (datetime.utcnow() +
                              api_settings.JWT_EXPIRATION_DELTA)
                response.set_cookie(api_settings.JWT_AUTH_COOKIE,
                                    token,
                                    expires=expiration,
                                    httponly=True)

            merge_cookie_cart_to_redis(request, user, response)
            return response

        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


# POST /browse_histories/
# 浏览记录添加
class BrowseHistoryView(CreateAPIView):
    '''浏览历史添加'''
    permission_classes = [IsAuthenticated]
    serializer_class = HistorySeralizer

    # def post(self, request):
    #     '''
    #     浏览历史记录添加
    #     1. 获取商品id 并校验 完整性, 对应商品是否存在
    #     2. 在redis中保存
    #     3. 返回响应
    #     :return:
    #     '''
    # # 1.获取商品id 并校验 完整性, 对应商品是否存在
    # serializer = self.get_serializer(data=request.data)
    # serializer.is_valid(raise_exception=True)
    # # 2.在redis中保存
    # serializer.save()
    # # 3. 返回响应
    # return Response(serializer.data,status=status.HTTP_201_CREATED)




    def get(self, request):
        '''
        获取用户的浏览记录
        1. 从redis 中获取用户浏览商品sku_id
        2. 根据商品sku_id 获取对应商品的信息
        3. 序列化返回商品数据

        '''
        # 1. 从redis 中获取用户浏览商品sku_id
        user = request.user
        redis_conn = get_redis_connection('histores')
        history_key = 'history_%s' % user.id

        sku_ids = redis_conn.lrange(history_key, 0, -1)

        # 2. 根据商品sku_id 获取对应商品的信息
        skus = []
        for sku_id in sku_ids:
            sku = SKU.objects.get(id=sku_id)
            skus.append(sku)
            # 3. 序列化返回商品数据
            serializers = SKUSerializers(skus, many=True)

        return Response(serializers.data)
